const fs = require('fs');
const request = require('request');
const xml2js = require('xml2js');
let parser = new xml2js.Parser({
    trim: true,
    explicitArray: false,
    explicitRoot: false
}); //解析签名结果xml转json
class companyPayment {
    /**------------------------------ 企业转账到微信零钱 ------------------------------*/
    // 生成XML函数
    async fnCreateXml(json) {
        let _xml = '';
        for (const key in json) {
            _xml += '<' + key + '>' + json[key] + '</' + key + '>';
        }
        return _xml;
    }

    // 生成url串用于微信md5校验
    async fnCreateUrlParam(json) {
        let _str = '';
        let _arr = [];
        for (const key in json) {
            _arr.push(key + '=' + json[key]);
        }
        return _arr.join('&');
    }


        // 生成红包xml参数数据
        async fnGetWeixinBonus(option) {
            console.log('option:', option);
            let amount = option.amount || 0;
            let re_openid = option.openid || '';
            let now = new Date();
            let send_name = config.zainaqypayment.send_name; // 公司名称
            let desc = config.zainaqypayment.desc; // 企业付款备注
            let mch_id = config.zainawxpa.merchantId; // 商户号
            let total_num = config.zainaqypayment.total_num; // 红包发放总人数
            let wishing = config.zainaqypayment.wishing; // 红包祝福语
            let client_ip = config.zainaqypayment.client_ip; // 调用接口的机器Ip地址
            let act_name = config.zainaqypayment.act_name; // 活动名称
            let remark = config.zainaqypayment.remark; // 备注
            let scene_id = config.zainaqypayment.scene_id; // 红包使用场景
            let wxappid = config.zainagzh.appid; // appid
            let wxkey = config.zainawxpa.payKey; // key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
            let check_name = config.zainaqypayment.check_name; // NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名
            let dateTime = now.getFullYear() + '' + (now.getMonth() + 1) + '' + now.getDate();
            let dateNo = (now.getTime() + '').substr(-8); // 生成8位日期数据，精确到毫秒
            let randomNo = Math.floor(Math.random() * 99);
            if (randomNo < 10) { // 生成2位随机数
                randomNo = '0' + randomNo;
            }
            let nonce_str = Math.random().toString(36).substr(2, 15); //生成随机字符串
            let mch_billno = mch_id + dateTime+ dateNo + randomNo;   //生成商户订单号
    
            let contentJson = {};
            // contentJson.check_name = check_name;// '强制验证名字';FORCE_CHECK
            // contentJson.desc = desc;//'恭喜发财';
            // contentJson.key = wxkey;  //微信安全密钥
            contentJson.act_name = act_name;
            contentJson.client_ip = client_ip;
            contentJson.mch_billno = mch_billno; 
            contentJson.mch_id = mch_id;
            contentJson.nonce_str = nonce_str;
            contentJson.remark = remark;
            contentJson.re_openid = re_openid;
            contentJson.scene_id = scene_id;
            contentJson.send_name = send_name;
            contentJson.total_amount = amount;
            contentJson.total_num = total_num; 
            contentJson.wishing = wishing; 
            contentJson.wxappid = wxappid;
            // 排序
            var newData = {};
            Object.keys(contentJson).sort().map(key => {
            newData[key]=contentJson[key]
            })

            // 生成url串用于微信md5校验
            let contentStr = await this.fnCreateUrlParam(newData);
            contentStr += `&key=${wxkey}`; // 拼接商户密匙
            console.log('content='+ contentStr);
            //生成签名
            let crypto = require('crypto');
            contentJson.sign = crypto.createHash('md5').update(contentStr, 'utf8').digest('hex').toUpperCase();
    
            //删除 contentJson对象中的key (key不参与签名)
            delete contentJson.key;
            //生成xml函数
            let xmlData = await this.fnCreateXml(contentJson);
            let sendData = '<xml>'+ xmlData +'</xml>'; //_xmlTemplate.replace(/{content}/)
            console.log('xml='+ sendData);
            return sendData;
        }

    async wxcompay(requ, callback) {
        let amount = parseInt(requ.amount * 100); //金额
        let openid = requ.openid;
        let option = {
            amount,
            openid
        };
        let sendData = await this.fnGetWeixinBonus(option);
        //读取微信生成的证书用作加密
        let opt = {
            url: "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack",
            body: sendData,
            // rejectUnauthorized: true,
            key: fs.readFileSync(process.cwd() + '/cert/zaina_payment_key.pem'), //将微信生成的证书放入 cert目录下
            cert: fs.readFileSync(process.cwd() + '/cert/zaina_payment_cert.pem'),
            // ca:fs.readFileSync(process.cwd() + '\\cert\\UDfVwcjBmWT6AmeE.p12').toString(),

        }
        return new Promise((resolve, reject) => {
            request.post(opt, function (err, res, body) {
                if (err) {
                    console.log('err:', err);
                    resolve({
                        flag: false
                    });
                }
                parser.parseString(body, function (err, res) {
                    console.log("res==", res);
                    if (res.result_code == 'SUCCESS') {
                        resolve({
                            flag: true,
                            respData: res
                        })
                    } else {
                        resolve({
                            flag: false,
                            respData: res
                        })
                    }
                })
            })
        })

    }
}

module.exports = companyPayment;